package com.example.share;


import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2024-03-02
 * Time: 16:36
 *
 * 共享域对象 request 获取和设置
 */

@Controller
@RequestMapping("/share")
@ResponseBody
public class ShareController {

    // 1. 原生 api，设置共享域对象
    @Autowired
    private ServletContext servletContext;


    public void data(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("name", "ws");
    }

    // 2. 通过 springMVC 提供的方法
    // model,modelMap,Map,modelAndView 设置共享域对象request
    public void data2(Model model) {
        model.addAttribute("name", "ws");
    }

    public void data3(ModelMap modelMap) {
        modelMap.addAttribute("name", "ws");
    }

    public void data4(Map<String, Object> map) {
        map.put("name", "ws");
    }

    public ModelAndView data5() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("name", "ws");
        modelAndView.setViewName("视图名，即页面名称");
        return modelAndView;
    }

}
